package com.none.web.service.news.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.DateUtil;
import com.none.core.common.utils.PathUtil;
import com.none.core.common.utils.ReplaceUtil;
import com.none.core.common.utils.StringUtil;
import com.none.core.common.utils.TransactSQLInjectionUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;



import com.none.web.common.SysConstant;
import com.none.web.common.bdPush.BaiduPushUtil;
import com.none.web.model.TActivity;
import com.none.web.model.TActivityImage;
import com.none.web.model.TBeacon;
import com.none.web.model.TNews;
import com.none.web.model.TNewsImage;
import com.none.web.model.TTags;
import com.none.web.model.TUser;
import com.none.web.model.T_ActivityAddnew_list;
import com.none.web.service.comments.ICommentsService;
import com.none.web.service.logs.ILogsService;
import com.none.web.service.news.INewsService;

/**
 * 新闻管理Service实现
 * 
 * @author Summer
 */
@Service("newsService")
public class NewsServiceImpl extends BaseServiceSupport implements INewsService {
	@Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
	com.none.web.service.activity.IActivityService iActivityService;
    @Autowired
	ILogsService logService;
    @Autowired
    ICommentsService  commentsService;
    
	@Override
	public boolean addNews(TNews news, String tags, String userId,String toBePostedTime,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.authorNull");
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");
		if (StringUtils.isBlank(news.getTitle()))
			throw new ValidateException("news.titleNull");
		if (StringUtils.isBlank(news.getPic()))
			throw new ValidateException("news.picIsNull");
		
		if (StringUtils.isNotEmpty(news.getBriefContent())) {
			if (news.getBriefContent().length() > 150) {
				throw new ValidateException("news.briefContentIsLong");
			}
		}else{
			throw new ValidateException("news.briefContentIsNull");
		}
		
		if (StringUtils.isBlank(news.getBriefContent()))
			throw new ValidateException("news.briefContentIsNull");
		
		if (StringUtils.isBlank(news.getContent()))
			throw new ValidateException("news.contentNull");
		if (StringUtils.isBlank(tags)) {
			throw new ValidateException("news.tagsNull");
		}
		// 设置添加人员
		TUser addUser = findEntity(TUser.class, userId);
		if (addUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (addUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		List<String> tagNames = StringUtil.split(tags, charSet);

		Criteria criteria = getCriteria(TNews.class);
		criteria.addOrder(Order.desc("newsId"));
		criteria.setMaxResults(1);
		List<?> newsList = criteria.list();
		// 设置主键
		int index = 0;
		if (newsList.size() > 0) {
			TNews tNews = (TNews) newsList.get(0);
			index = tNews.getNewsId();
		}
		news.setNewsId(index + 1);

		news.setAuthorUser(addUser);
		// 设置新闻的状态
		if ("reviewer".equals(addUser.getUserType())) {
			news.setStatus("Published");
			news.setApprovalUser(addUser);
			news.setApprovalTime(new Timestamp(new Date().getTime()));
			news.setSubmit_time(new Timestamp(new Date().getTime()));
			news.setSubmit_user_id(userId);
		} else {
			news.setStatus("Pending Review");
			news.setSubmit_time(new Timestamp(new Date().getTime()));
			news.setSubmit_user_id(userId);
		}
		if(StringUtils.isNotBlank(toBePostedTime)&&!toBePostedTime.equals("NaN")){
			news.setToBePostedTime(new Timestamp(Long.valueOf(toBePostedTime)));
		}else{
			news.setToBePostedTime(new Timestamp(new Date().getTime()));
		}
		// 设置添加时间
		news.setAddTime(new Timestamp(new Date().getTime()));
		news.setEditTime(new Timestamp(new Date().getTime()));
		news.setUpdateUser(addUser);
		// 设置新闻类型
		news.setType("news");
//		String content = StringUtil.toStringNoTrim(news.getContent());
//		if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//			news.setType("video");
//		}else{
//			news.setType("news");
//		}
    	news.setPush_count(0);
    	if(push==null||"".equals(push)){
    		news.setPush("no");
    	}else{
    		news.setPush(push);
    	}
		// 添加tags
		if (tagNames != null) {
			// 设置Tags
			Set<TTags> tages = new HashSet<TTags>();
			for (String tagName : tagNames) {
				TTags tag = null;
				Criteria tagCriteria = getCriteria(TTags.class);
				tagCriteria.add(Restrictions.eq("name", tagName));
				List<?> userList = tagCriteria.list();
				if (userList.size() > 1 || userList.size() < 0) {
					// new ValidateException("common.sysException");
					continue;
				} else if (userList.size() == 0) {
					tag = new TTags();
					tag.setTagId(CreateID.getID());
					tag.setName(tagName);
				} else if (userList.size() == 1) {
					tag = (TTags) userList.get(0);
				}
				tages.add(tag);
			}
			news.setTTagses(tages);
		}
		if (StringUtils.isNotBlank(news.getContent())){
			news.setContent(ReplaceUtil.replaceSomeString(news.getContent(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
		}
		// 保存
		news.setPushInfo(pushcontent);
		
		//推送
		if("Published".equals(news.getStatus())){
			if("push".equals(push)&&news.getPush_count()==0){//是否push
					//this.push_bd(news.getTitle(), news.getBriefContent(), "ios", null,"new", news.getNewsId()+"");
					//this.push_bd(news.getTitle(), news.getBriefContent(), "android", null, "new", news.getNewsId()+"");
				BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"new", news.getNewsId()+"");
				BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "new", news.getNewsId()+"");
				Integer push_count=0;
				if(news.getPush_count()!=null){
					push_count=news.getPush_count();
				}
				news.setPush_count(push_count+1);
				//updateEntity(news);
			}
		}
		
		if (saveEntity(news) == null) {
			throw new ValidateException("common.illegalRequest");
		} else {
			return true;
		}
		//return false;
	}

	@Override
	public boolean saveDraft(TNews news, String tags, String userId,String toBePostedTime,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.authorNull");
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");
		if (StringUtils.isBlank(news.getTitle()))
			throw new ValidateException("news.titleNull");
		if (StringUtils.isNotEmpty(news.getBriefContent())) {
			if (news.getBriefContent().length() > 150) {
				throw new ValidateException("news.briefContentIsLong");
			}
		}
		// if (StringUtils.isBlank(news.getContent()))
		// throw new ValidateException("news.contentNull");
		//
		 if (StringUtils.isBlank(tags)) {
		 throw new ValidateException("news.tagsNull");
		 }

		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		List<String> tagNames = StringUtil.split(tags, charSet);
		// 设置添加人员
		TUser addUser = findEntity(TUser.class, userId);
		if (addUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (addUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

		if (news.getNewsId() == null) {
			Criteria criteria = getCriteria(TNews.class);
			criteria.addOrder(Order.desc("newsId"));
			criteria.setMaxResults(1);
			List<?> newsList = criteria.list();
			// 设置主键
			int index = 0;
			if (newsList.size() > 0) {
				TNews tNews = (TNews) newsList.get(0);
				index = tNews.getNewsId();
			}
			news.setNewsId(index + 1);
			// 设置添加人员
			news.setAuthorUser(addUser);
			// 设置新闻的状态
			if(news.getStatus().equals("Draft")){
				news.setStatus("Draft");
			}else if(news.getStatus().equals("Submit")){
				news.setStatus("Pending Review");
				news.setSubmit_time(new Timestamp(new Date().getTime()));
				news.setSubmit_user_id(userId);
			}else if(news.getStatus().equals("Publish")){
				if (!"reviewer".equals(addUser.getUserType())) {
					throw new ValidateException("common.illegalRequest");
				}
				news.setApprovalUser(addUser);
				news.setApprovalTime(new Timestamp(new Date().getTime()));
				news.setStatus("Published");
				news.setSubmit_time(new Timestamp(new Date().getTime()));
				news.setSubmit_user_id(userId);
			}/*else{
				throw new ValidateException("common.illegalRequest");
			}*/
			// set toBePostedTime
			if(StringUtils.isNotBlank(toBePostedTime)&&!toBePostedTime.equals("NaN")){
				news.setToBePostedTime(new Timestamp(Long.valueOf(toBePostedTime)));
			}else{
				news.setToBePostedTime(new Timestamp(new Date().getTime()));
			}
			// 设置添加时间
			Timestamp timeStamp = new Timestamp(new Date().getTime());
			news.setAddTime(timeStamp);
			news.setEditTime(timeStamp);
			// 设置修改人员
			news.setUpdateUser(addUser);
			// 设置新闻类型
			news.setType("news");
//			String content = StringUtil.toStringNoTrim(news.getContent());
//			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//				news.setType("video");
//			}else{
//				news.setType("news");
//			}
			// 添加tags
			if (tagNames != null) {
				// 设置Tags
				Set<TTags> tages = new HashSet<TTags>();
				for (String tagName : tagNames) {
					TTags tag = null;
					Criteria tagCriteria = getCriteria(TTags.class);
					tagCriteria.add(Restrictions.eq("name", tagName));
					List<?> userList = tagCriteria.list();
					if (userList.size() > 1 || userList.size() < 0) {
						continue;
					} else if (userList.size() == 0) {
						tag = new TTags();
						tag.setTagId(CreateID.getID());
						tag.setName(tagName);
					} else if (userList.size() == 1) {
						tag = (TTags) userList.get(0);
					}
					tages.add(tag);
				}
				news.setTTagses(tages);
			}
			news.setPush_count(0);
	    	if(push==null||"".equals(push)){
	    		news.setPush("no");
	    	}else{
	    		news.setPush(push);
	    	}
			// 保存
	    	news.setPushInfo(pushcontent);
	    	if (StringUtils.isNotBlank(news.getContent())){
	    		news.setContent(ReplaceUtil.replaceSomeString(news.getContent(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
	    	}
	    	
	    	//推送
			if("Published".equals(news.getStatus())){
				if("push".equals(push)&&news.getPush_count()==0){//是否push
					//this.push_bd(news.getTitle(), news.getBriefContent(), "ios", null,"new", news.getNewsId()+"");
					//this.push_bd(news.getTitle(), news.getBriefContent(), "android", null, "new", news.getNewsId()+"");
					BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"new", news.getNewsId()+"");
					BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "new", news.getNewsId()+"");
					Integer push_count=0;
					if(news.getPush_count()!=null){
						push_count=news.getPush_count();
					}
					news.setPush_count(push_count+1);
					//updateEntity(news);
				}
			}
	    	
	    	if (saveEntity(news) == null) {
				throw new ValidateException("common.illegalRequest");
			}
			
			//save image list
			if(news.getImageList()!=null && news.getImageList().size()>0){
				for (int i = 0; i < news.getImageList().size(); i++) {
					TNewsImage image = news.getImageList().get(i);
					image.setNewsId(news.getNewsId());
					if (saveEntity(image) == null) {
							throw new ValidateException("common.illegalRequest");
					}
				}
			}
		} else {
			TNews tNews = findEntity(TNews.class, news.getNewsId());
			if (tNews != null) {
				//modify william at 2014-12-18 for open edit
				// 审核通过的新闻不能修改
				/*if ("Published".equals(tNews.getStatus())) {
					//throw new ValidateException("news.publishedNotUpdate");
				} else if ("Pending Review".equals(tNews.getStatus())) {// 新闻等待审核状态，只有审核人员才能修改
					//throw new ValidateException("news.pedingNotRight");
				} else {
					// 新闻为草稿，只能是发布者才能修改
					if ("Draft".equals(tNews.getStatus())) {
						if (!userId.equals(tNews.getAuthorUser().getUserId())) {
							throw new ValidateException("news.notAuthor");
						}
					}else{
						// 设置新闻的状态
						tNews.setStatus("Draft");
					}
				}*/
				
				if ("Published".equals(tNews.getStatus())) {
					// 审核通过的新闻只有发布者与审核者才能编辑
					if (!"reviewer".equals(addUser.getUserType())) {
						throw new ValidateException("news.pedingNotRight");
					}
					// 设置新闻的状态
					if(news.getStatus().equals("Draft")){
						tNews.setStatus("Draft");
					}else if(news.getStatus().equals("Submit")){
						tNews.setStatus("Pending Review");
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
						tNews.setSubmit_user_id(userId);
					}else if(news.getStatus().equals("Publish")){
						if (!"reviewer".equals(addUser.getUserType())) {
							throw new ValidateException("common.illegalRequest");
						}
						tNews.setApprovalUser(addUser);
						tNews.setApprovalTime(new Timestamp(new Date().getTime()));
						tNews.setStatus("Published");
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
						tNews.setSubmit_user_id(userId);
					}
				}else if ("Draft".equals(tNews.getStatus())) {
					// 新闻为草稿，只能是发布者才能修改
//					if (!userId.equals(tNews.getAuthorUser().getUserId())) {
//						throw new ValidateException("news.notAuthor");
//					}
					// 设置新闻的状态
					if(news.getStatus().equals("Submit")){
						tNews.setStatus("Pending Review");
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
						tNews.setSubmit_user_id(userId);
					}else if(news.getStatus().equals("Publish")){
						if (!"reviewer".equals(addUser.getUserType())) {
							throw new ValidateException("common.illegalRequest");
						}
						tNews.setApprovalUser(addUser);
						tNews.setApprovalTime(new Timestamp(new Date().getTime()));
						tNews.setStatus("Published");
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
						tNews.setSubmit_user_id(userId);
					}
				} else if ("Pending Review".equals(tNews.getStatus())) {
					// 新闻等待审核状态，只有审核人员才能修改
					if ("reporter".equals(addUser.getUserType())) {
						throw new ValidateException("news.pedingNotRight");
					}
					// 设置新闻的状态
					 if(news.getStatus().equals("Publish")){
						if (!"reviewer".equals(addUser.getUserType())) {
							throw new ValidateException("common.illegalRequest");
						}
						tNews.setApprovalUser(addUser);
						tNews.setApprovalTime(new Timestamp(new Date().getTime()));
						tNews.setStatus("Published");
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
						tNews.setSubmit_user_id(userId);
					}
				}/*else{
					throw new ValidateException("common.illegalRequest");
				}*/
				//update to new
//				if (!userId.equals(tNews.getAuthorUser().getUserId())) {
//					throw new ValidateException("news.notAuthor");
//				}
				if (StringUtils.isNotBlank(news.getContent())) {
					tNews.setContent(news.getContent());
				}
				if (StringUtils.isNotBlank(news.getTitle())) {
					tNews.setTitle(news.getTitle());
				}
				if (StringUtils.isNotBlank(news.getBriefContent())) {
					tNews.setBriefContent(news.getBriefContent());
				}
				if (StringUtils.isNotBlank(news.getPic())) {
					tNews.setPic(news.getPic());
				}
				// 设置Tags
				Set<TTags> tages = new HashSet<TTags>();
				for (String tagName : tagNames) {
					TTags tag = null;
					Criteria tagCriteria = getCriteria(TTags.class);
					tagCriteria.add(Restrictions.eq("name", tagName));
					List<?> userList = tagCriteria.list();
					if (userList.size() > 1 || userList.size() < 0) {
						// new ValidateException("common.sysException");
						continue;
					} else if (userList.size() == 0) {
						tag = new TTags();
						tag.setTagId(CreateID.getID());
						tag.setName(tagName);
					} else if (userList.size() == 1) {
						tag = (TTags) userList.get(0);
					}

					tages.add(tag);
				}
				tNews.setTTagses(tages);
				// 设置修改人员
				tNews.setUpdateUser(addUser);
				// 设置修改时间
				tNews.setEditTime(new Timestamp(new Date().getTime()));
				tNews.setVideo(news.getVideo());
				tNews.setVideoPrevPic(news.getVideoPrevPic());
				// set toBePostedTime
				if(StringUtils.isNotBlank(toBePostedTime)&&!toBePostedTime.equals("NaN")){
					tNews.setToBePostedTime(new Timestamp(Long.valueOf(toBePostedTime)));
				}else{
					tNews.setToBePostedTime(new Timestamp(new Date().getTime()));
				}
				tNews.setType("news");
//				String content = StringUtil.toStringNoTrim(tNews.getContent());
//				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//					tNews.setType("video");
//				}else{
//					tNews.setType("news");
//				}
				if(tNews.getPush_count()==null){
					tNews.setPush_count(0);
				}
		    	if(push==null||"".equals(push)){
		    		tNews.setPush("no");
		    	}else{
		    		tNews.setPush(push);
		    	}
		    	if (StringUtils.isNotBlank(tNews.getContent())){
		    		tNews.setContent(ReplaceUtil.replaceSomeString(tNews.getContent(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
		    	}
		    	//
		    	tNews.setPushInfo(pushcontent);
				
				//推送
				if("Published".equals(tNews.getStatus())){
					if("push".equals(push)&&tNews.getPush_count()==0){//是否push
						//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "ios", null,"new", tNews.getNewsId()+"");
						//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "android", null, "new", tNews.getNewsId()+"");
						BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"new", tNews.getNewsId()+"");
						BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "new", tNews.getNewsId()+"");
						Integer push_count=0;
						if(tNews.getPush_count()!=null){
							push_count=tNews.getPush_count();
						}
						tNews.setPush_count(push_count+1);
						//updateEntity(tNews);
					}
				}
				
				updateEntity(tNews);
				//delete image list
				String delSql="delete from t_news_image where news_id='"+tNews.getNewsId()+"'";
				this.jdbcTemplate.execute(delSql);
				//save image list
				if(news.getImageList()!=null && news.getImageList().size()>0){
					for (int i = 0; i < news.getImageList().size(); i++) {
						TNewsImage image = news.getImageList().get(i);
						image.setNewsId(news.getNewsId());
						if (saveEntity(image) == null) {
								throw new ValidateException("common.illegalRequest");
						}
					}
				}
			}
		}
		return true;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object listNews(Pager pager, String keyword, String tagNames,String userId,String type) throws Exception{
		// 分割tag标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		// TUser listUser = findEntity(TUser.class, userId);

		Criteria criteria = getCriteria(TNews.class);
		if(!"".equals(type)&& type!=null){
			criteria.add(Restrictions.eq("type", type));
		}
		

		if (StringUtils.isNotBlank(keyword)) {
			criteria.add(Restrictions.or(Restrictions.like("title", "%" + keyword + "%"),
					Restrictions.like("content", "%" + keyword + "%")));
		}
		if (StringUtils.isNotBlank(tagNames)) {
			List<String> tagName = StringUtil.split(tagNames, charSet);
			Criteria tagCriteria = getCriteria(TTags.class);

			tagCriteria.add(Restrictions.in("name", tagName));
			@SuppressWarnings("unchecked")
			List<TTags> tTagsList = tagCriteria.list();
			List<Integer> newIds = new ArrayList<Integer>();
			for (TTags tTags : tTagsList) {
				for (TNews news : tTags.getTNewses()) {
					newIds.add(news.getNewsId());
				}
			}
			if (newIds.size() > 0) {
				criteria.add(Restrictions.in("newsId", newIds));
			}else{
				return new ArrayList<TNews>();
			}
			// criteria.createAlias("TTagses", "tag");
			// criteria.add(Restrictions.in("tag.name", tagName));
		}

		criteria.add(Restrictions.eq("status", "Published"));

		criteria.addOrder(Order.desc("addTime"));
		List<TNews> listNews = new ArrayList<TNews>();
		@SuppressWarnings("unchecked")
		List<TNews> list = (List<TNews>) listPageQBCL(criteria, pager);
		
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			TNews tNews = (TNews) iterator.next();

			//add by Bing 2015-08-05
			String content = StringUtil.toStringNoTrim(tNews.getContent());
			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
				tNews.setVideoFlag("video");
			}else{
				tNews.setVideoFlag("notvideo");
			}
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="";
			if(type==null||"".equals(type)){
				likeSql="select count(t.id) num from t_like t where  t.contentId='"+tNews.getNewsId()+"' and t.delete_flag='0'";
			}else{
				likeSql="select count(t.id) num from t_like t where t.type='"+type+"' and t.contentId='"+tNews.getNewsId()+"' and t.delete_flag='0'";
			}
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tNews.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tNews.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="";
			if(type==null||"".equals(type)){
				islikeSql="select count(t.id) num from t_like t where  t.contentId='"+tNews.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			}else{
				islikeSql="select count(t.id) num from t_like t where t.type='"+type+"' and t.contentId='"+tNews.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			}
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tNews.setLike(true);
			}else{
				tNews.setLike(false);
			}
			
			//设置浏览数量(同一人多次浏览算一次)  Add by Bing 2015-07-07
			if(type==null||"".equals(type)){
				tNews.setBrowseTimes(logService.getBrowseTimes(tNews.getNewsId()+"", "", userId));
			}else{
				tNews.setBrowseTimes(logService.getBrowseTimes(tNews.getNewsId()+"", type, userId));
			}
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			if(type==null||"".equals(type)){
				tNews.setAllBrowseTimes(logService.getAllBrowseTimes(tNews.getNewsId()+"", "", userId));
			}else{
				tNews.setAllBrowseTimes(logService.getAllBrowseTimes(tNews.getNewsId()+"", type, userId));
			}
			
			
			//设置评论  Add by Bing 2015-07-07
//			List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="";
//			if(type==null||"".equals(type)){
//				commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.contentId='"+tNews.getNewsId()+"' order by t.publish_time desc";
//			}else{
//				commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='"+type+"' and t.contentId='"+tNews.getNewsId()+"' order by t.publish_time desc";
//			}
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int i=0;i<listMapComment.size();i++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//					comment.setUserId(userid);
//					//登录人可以删除自己的评论，不能删除其他人的
//					if(userid.equals(userId)){
//						comment.setCanDelete(true);
//					}else{
//						comment.setCanDelete(false);
//					}
//					comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tNews.setCommentList(commentList);
//			}
			
			//设置评论数量  Add by Bing 2015-07-07
			tNews.setCommentAmount(commentsService.getCommentsAmount(tNews.getNewsId()+"", ""));
			listNews.add(tNews);
		}
		return listNews;
	}
	@SuppressWarnings({ "unchecked"})
	public Object listNewsActivitys(Pager pager, String keyword, String tagNames,String type,String userId) throws Exception{
		//sql语句一，适合通过keyword和标签同时查询 和 只通过标签查询
		String sql_tags_tagIds="''";
		Criteria tagCriteriaNow = getCriteria(TTags.class);
		tagCriteriaNow.add(Restrictions.eq("name", "NOW"));
		List<TTags> tTagsListNow = tagCriteriaNow.list();
		String tagId = tTagsListNow.get(0).getTagId();
		
		StringBuffer sql_tags =new StringBuffer();
		sql_tags.append(" select * from (");
		
		if("hbcnNow".equals(type)){
			sql_tags.append(" selectbytagsandtagisnotnullactivity select activity_ids.* from (select activity_obj.* from (select an.id,an.obj_id,an.obj_type,an.report_time  from t_activityAddnew_list an , t_activity a ");
			sql_tags.append("   where a.id=an.obj_id and  an.obj_type='a' and a.status=2 ");
			sql_tags.append(" activ_keyword_search_mm ");
			sql_tags.append(" ) as activity_obj   ");
			sql_tags.append(" ,  (select activity_id from t_activity_tag where tag_id in ('"+tagId+"')  group by activity_id ) as tag_activity where tag_activity.activity_id=activity_obj.obj_id ) as activity_ids queryformresultactivity");
		}else{
			sql_tags.append(" select activity_ids.* from (select activity_obj.* from (select an.id,an.obj_id,an.obj_type,an.report_time  from t_activityAddnew_list an , t_activity a ");
			sql_tags.append("   where a.id=an.obj_id and  an.obj_type='a' and a.status=2 ");
			sql_tags.append(" activ_keyword_search_mm ");
			sql_tags.append(" ) as activity_obj   ");
			sql_tags.append(" ,  (select activity_id from t_activity_tag where tag_id in (use_filter_tagIds)  group by activity_id ) as tag_activity where tag_activity.activity_id=activity_obj.obj_id ) as activity_ids ");
		}
				
		sql_tags.append(" union ");
		
		if("hbcnNow".equals(type)){
			sql_tags.append(" selectbytagsandtagisnotnullnews select new_ids.* from (  select new_obj.* from (select an.id,an.obj_id,an.obj_type,an.report_time  from t_activityAddnew_list an , t_news a    where a.news_id=an.obj_id  and a.status='Published' and (a.to_bePosted_time is null or a.to_bePosted_time<='"+new Timestamp(new Date().getTime())+"')");
			sql_tags.append(" news_keyword_search_mm ");
			sql_tags.append(" ) as new_obj   ");
			sql_tags.append("  ,  (select news_id from t_new_tag where tag_id in ('"+tagId+"')  group by news_id ) as tag_new where tag_new.news_id=new_obj.obj_id  ) as new_ids  queryformresultnews");
		}else{
			sql_tags.append(" select new_ids.* from (  select new_obj.* from (select an.id,an.obj_id,an.obj_type,an.report_time  from t_activityAddnew_list an , t_news a    where a.news_id=an.obj_id  and a.status='Published' and (a.to_bePosted_time is null or a.to_bePosted_time<='"+new Timestamp(new Date().getTime())+"')");
			sql_tags.append(" news_keyword_search_mm ");
			sql_tags.append(" ) as new_obj   ");
			sql_tags.append("  ,  (select news_id from t_new_tag where tag_id in (use_filter_tagIds)  group by news_id ) as tag_new where tag_new.news_id=new_obj.obj_id  ) as new_ids ");
		}
		
				
		sql_tags.append(" ) as count_1   order by count_1.report_time  desc ");
		
		String sql_keywords=" select * from (  "
				+ " select an.id,an.obj_id,an.obj_type,an.report_time  from t_activityAddnew_list an , t_activity a  activityTags  where a.id=an.obj_id  and  an.obj_type='a' and a.status=2  conditionActivityTags  activ_keyword_search_mm  union "
				+ " select an.id,an.obj_id,an.obj_type,an.report_time  from t_activityAddnew_list an , t_news a  newsTags  where a.news_id=an.obj_id  and a.status='Published' and (a.to_bePosted_time is null or a.to_bePosted_time<='"+new Timestamp(new Date().getTime())+"')  conditionNewsTags news_keyword_search_mm  "
				+ ") as count_1 "
				+ "order by count_1.report_time desc ";
		
		// 分割tag标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		if(tagNames!=null&&!"".equals(tagNames)){
			List<String> tagName = StringUtil.split(tagNames, charSet);
			Criteria tagCriteria = getCriteria(TTags.class);
			tagCriteria.add(Restrictions.in("name", tagName));
			List<TTags> tTagsList = tagCriteria.list();
			String tagIds = "";
			for (TTags tag : tTagsList) {
				tagIds=tagIds+"'"+tag.getTagId()+"',";
			}
			if(!"".equals(tagIds)){
				tagIds=tagIds.substring(0,tagIds.length()-1);
				sql_tags_tagIds=tagIds;
			}
		}
		
		String sql = sql_tags.toString();
		
		//标签
		if(StringUtils.isNotBlank(tagNames)){
			//关键字
			if(StringUtils.isNotBlank(keyword)){
				sql=sql.replace("activ_keyword_search_mm", " and (a.brief_content like '%"+keyword+"%' or a.subject like '%"+keyword+"%'  ) "); 
				sql=sql.replace("news_keyword_search_mm", "and (a.title like '%"+keyword+"%' or a.brief_content like '%"+keyword+"%') ");
			}else{
				sql=sql.replace("activ_keyword_search_mm", " ");
				sql=sql.replace("news_keyword_search_mm", " ");
			}
			sql=sql.replaceAll("selectbytagsandtagisnotnullactivity", "select resb.* from (");
			sql=sql.replaceAll("queryformresultactivity", ",(select activity_id from t_activity_tag where tag_id in(use_filter_tagIds) group by activity_id) as tagactivity  where activity_ids.obj_id=tagactivity.activity_id) resb ");
			
			sql=sql.replaceAll("selectbytagsandtagisnotnullnews", "select resa.* from (");
			sql=sql.replaceAll("queryformresultnews", ",(select news_id from t_new_tag where tag_id in(use_filter_tagIds) group by news_id) as tagnews  where new_ids.obj_id=tagnews.news_id) resa ");
			
			sql=sql.replaceAll("use_filter_tagIds", sql_tags_tagIds);
		}else{
			sql=sql_keywords;
			if(StringUtils.isNotBlank(keyword)){
				sql=sql.replace("activ_keyword_search_mm", " and (a.brief_content like '%"+keyword+"%' or a.subject like '%"+keyword+"%'  ) "); 
				sql=sql.replace("news_keyword_search_mm", "and (a.title like '%"+keyword+"%' or a.brief_content like '%"+keyword+"%') ");
			}else{
				sql=sql.replace("activ_keyword_search_mm", " ");
				sql=sql.replace("news_keyword_search_mm", " ");
			}
			if("hbcnNow".equals(type)){
				sql=sql.replace("activityTags", ",t_activity_tag activitytags");
				sql=sql.replace("conditionActivityTags", "and an.obj_id=activitytags.activity_id and activitytags.tag_id='"+tagId+"'");
				sql=sql.replace("newsTags", ",t_new_tag newstags");
				sql=sql.replace("conditionNewsTags", "and an.obj_id=newstags.news_id and newstags.tag_id='"+tagId+"'");
			}else{
				sql=sql.replace("activityTags", " ");
				sql=sql.replace("conditionActivityTags", " ");
				sql=sql.replace("newsTags", " ");
				sql=sql.replace("conditionNewsTags", " ");
			}
			
		}
		/**
		 * 2015-7-24   bing 注释
		 */
		//第一种情况，通过标签和keyword查询。
//		if (StringUtils.isNotBlank(tagNames)&&StringUtils.isBlank(keyword)) {
//			sql=sql.replace("activ_keyword_search_mm", " ");
//			sql=sql.replace("news_keyword_search_mm", " ");
//			//sql_tags=sql_tags.replace("videos_keyword_search_mm", " ");
//			sql=sql.replaceAll("use_filter_tagIds", sql_tags_tagIds);
//			sql=sql.replaceAll("selectbytagsandtagisnotnull", "select resa.* from (");
//			sql=sql.replaceAll("queryformresult", ",(select news_id from t_new_tag where tag_id in(use_filter_tagIds) group by news_id) as tag  where new_ids.obj_id=tag.news_id) resa ");
//		}
//		else if(StringUtils.isNotBlank(tagNames)&&StringUtils.isNotBlank(keyword)){
//			sql=sql.replace("activ_keyword_search_mm", " and (a.brief_content like '%"+keyword+"%' or a.subject like '%"+keyword+"%'  ) "); 
//			sql=sql.replace("news_keyword_search_mm", "and (a.title like '%"+keyword+"%' or a.brief_content like '%"+keyword+"%') ");
//			//sql_tags=sql_tags.replace("videos_keyword_search_mm", "and (a.title like '%"+keyword+"%' or a.brief_content like '%"+keyword+"%') ");
//			sql=sql.replaceAll("use_filter_tagIds", sql_tags_tagIds);
//		}else if(StringUtils.isBlank(tagNames)&&StringUtils.isNotBlank(keyword)){
//			//sql=sql_keywords;
//			sql=sql.replace("activ_keyword_search_mm", " and (a.brief_content like '%"+keyword+"%' or a.subject like '%"+keyword+"%') "); 
//			sql=sql.replace("news_keyword_search_mm", " and  (a.title like '%"+keyword+"%' or a.brief_content like '%"+keyword+"%') ");
//			//sql_tags=sql_tags.replace("videos_keyword_search_mm", "and (a.title like '%"+keyword+"%' or a.brief_content like '%"+keyword+"%') ");
//		}else{
//			//sql=sql_keywords;
//			sql=sql.replace("activ_keyword_search_mm", " "); 
//			sql=sql.replace("news_keyword_search_mm", " ");
//			//sql_tags=sql_tags.replace("videos_keyword_search_mm", " ");
//		}
		//System.out.println("##############"+sql);
		List<T_ActivityAddnew_list>  list=(List<T_ActivityAddnew_list>) this.getListBySql(pager, sql, T_ActivityAddnew_list.class);
		List<Object> objList=new ArrayList<Object>();
		if(list!=null){
			for(T_ActivityAddnew_list ac_new:list){
				if(ac_new!=null){
					TNews newobj=null;
					TActivity act=null;
					//TVideos video=null;
					if("a".equals(ac_new.getObj_type())){
						act= findEntity(TActivity.class, ac_new.getObj_id());
						act.setTypes("activity");
						//add by william 2014-12-11
						Criteria activityImageCriteria = getCriteria(TActivityImage.class);
						activityImageCriteria.add(Restrictions.eq("activityId", ac_new.getObj_id()));
						activityImageCriteria.addOrder(Order.asc("orderIndex"));
						act.setImageList(activityImageCriteria.list());
						
						act.setFlag(iActivityService.checkActivity(ac_new.getObj_id(), userId));
						
						String content = act.getDescription();
						if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
							act.setVideoFlag("video");
						}else{
							act.setVideoFlag("notvideo");
						}
						
						//设置点赞数量   Add by Bing 2015-07-07
						String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+act.getId()+"' and t.delete_flag='0'";
						List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
						if(listMapLike!=null && listMapLike.size()>0){
							act.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
						}else{
							act.setLikeAmount(0);
						}
						
						//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
						String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+act.getId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
						List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
						Integer amount=0;
						if(listMapIsLike!=null && listMapIsLike.size()>0){
							amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
						}else{
							amount=0;
						}
						if(amount>0){
							act.setLike(true);
						}else{
							act.setLike(false);
						}
						
						//设置浏览数量  Add by Bing 2015-07-07
						act.setBrowseTimes(logService.getBrowseTimes(act.getId(), "activity", userId));
						
						//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
						act.setAllBrowseTimes(logService.getAllBrowseTimes(act.getId()+"", "activity", userId));
						
						//设置评论  Add by Bing 2015-07-07
//						List<TComments> commentList = new ArrayList<TComments>();
//						String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+act.getId()+"' order by t.publish_time desc";
//						List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//						if(listMapComment!=null && listMapComment.size()>0){
//							for(int i=0;i<listMapComment.size();i++){
//								TComments comment=new TComments();
//								comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//								String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//								comment.setUserId(userid);
//								//登录人可以删除自己的评论，不能删除其他人的
//								if(userid.equals(userId)){
//									comment.setCanDelete(true);
//								}else{
//									comment.setCanDelete(false);
//								}
//								comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//								comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//								comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//								String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//								comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//								
//								commentList.add(comment);
//							}
//							act.setCommentList(commentList);
//						}
						
						//设置评论数量  Add by Bing 2015-07-07
						act.setCommentAmount(commentsService.getCommentsAmount(act.getId()+"", "activity"));
					//}else if("news".equals(ac_new.getObj_type())||"video".equals(ac_new.getObj_type())){
					}else if("n".equals(ac_new.getObj_type())){
						newobj= findEntity(TNews.class, Integer.valueOf(ac_new.getObj_id()));
						newobj.setTypes("new");
						//add by william 2014-12-11
						Criteria newsImageCriteria = getCriteria(TNewsImage.class);
						newsImageCriteria.add(Restrictions.eq("newsId",Integer.valueOf(ac_new.getObj_id())));
						newsImageCriteria.addOrder(Order.asc("orderIndex"));
						newobj.setImageList(newsImageCriteria.list());
						
						//add by Bing 2015-08-05
						String content = StringUtil.toStringNoTrim(newobj.getContent());
						if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
							newobj.setVideoFlag("video");
						}else{
							newobj.setVideoFlag("notvideo");
						}
						
						//设置点赞数量   Add by Bing 2015-07-07
						String likeSql="select count(t.id) num from t_like t where  t.contentId='"+newobj.getNewsId()+"' and t.delete_flag='0'";
						List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
						if(listMapLike!=null && listMapLike.size()>0){
							newobj.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
						}else{
							newobj.setLikeAmount(0);
						}
						
						//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
						String islikeSql="select count(t.id) num from t_like t where  t.contentId='"+newobj.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
						List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
						Integer amount=0;
						if(listMapIsLike!=null && listMapIsLike.size()>0){
							amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
						}else{
							amount=0;
						}
						if(amount>0){
							newobj.setLike(true);
						}else{
							newobj.setLike(false);
						}
						
						//设置浏览数量  Add by Bing 2015-07-07
						newobj.setBrowseTimes(logService.getBrowseTimes(newobj.getNewsId()+"", "", userId));
						
						//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
						newobj.setAllBrowseTimes(logService.getAllBrowseTimes(newobj.getNewsId()+"", "", userId));
						
						//设置评论  Add by Bing 2015-07-07
//						List<TComments> commentList = new ArrayList<TComments>();
//						String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id  and t.contentId='"+newobj.getNewsId()+"' order by t.publish_time desc";
//						List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//						if(listMapComment!=null && listMapComment.size()>0){
//							for(int i=0;i<listMapComment.size();i++){
//								TComments comment=new TComments();
//								comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//								String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//								comment.setUserId(userid);
//								//登录人可以删除自己的评论，不能删除其他人的
//								if(userid.equals(userId)){
//									comment.setCanDelete(true);
//								}else{
//									comment.setCanDelete(false);
//								}
//								comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//								comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//								comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//								String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//								comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//								
//								commentList.add(comment);
//							}
//							newobj.setCommentList(commentList);
//						}
						
						//设置评论数量  Add by Bing 2015-07-07
						newobj.setCommentAmount(commentsService.getCommentsAmount(newobj.getNewsId()+"", ""));
					}
					if(newobj!=null){
						objList.add(newobj);
					}
					if(act!=null){
						objList.add(act);
					}
				}
			}
		}
		return objList;
	}

	@SuppressWarnings({ "unchecked", "rawtypes"})
	@Override
	public Object searchNews(Pager pager, String keyword, String tagName, String fromDate, String toDate, String userId)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 分割tag标签
		TUser listUser = findEntity(TUser.class, userId);
		if (listUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		Criteria criteria = getCriteria(TNews.class);
//
//		if (StringUtils.isNotBlank(keyword)) {
//			criteria.add(Restrictions.or(Restrictions.like("title", "%" + keyword + "%"),
//					Restrictions.like("content", "%" + keyword + "%")));
//		}
//		if (StringUtils.isNotBlank(tagName)) {
//			String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
//			List<String> tagNames = StringUtil.split(tagName, charSet);
//			Criteria tagCriteria = getCriteria(TTags.class);
//
//			tagCriteria.add(Restrictions.in("name", tagNames));
//			List<TTags> tTagsList = tagCriteria.list();
//			List<Integer> newIds = new ArrayList<Integer>();
//			for (TTags tTags : tTagsList) {
//				for (TNews news : tTags.getTNewses()) {
//					newIds.add(news.getNewsId());
//				}
//			}
//			if (newIds.size() > 0) {
//				criteria.add(Restrictions.in("newsId", newIds));
//			}else{
//				return new ArrayList<TNews>();
//			}
////			criteria.createAlias("TTagses", "tag");
////			criteria.add(Restrictions.in("tag.name", tagNames));
//		}
//		if (StringUtils.isNotBlank(fromDate) && StringUtils.isNotBlank(toDate)) {
//			criteria.add(Restrictions.between("addTime", this.updateDate(this.getDate(fromDate), "start"), this.updateDate(this.getDate(toDate), "end")));
//		} else if (StringUtils.isNotBlank(fromDate)) {
//			criteria.add(Restrictions.ge("addTime", this.updateDate(this.getDate(fromDate), "start")));
//		} else if (StringUtils.isNotBlank(toDate)) {
//			criteria.add(Restrictions.le("addTime", this.updateDate(this.getDate(toDate), "end")));
//		}
//		criteria.setFetchMode("au",FetchMode.JOIN); 
//		criteria.setFetchMode("app",FetchMode.JOIN); 
//		criteria.setFetchMode("up",FetchMode.JOIN); 
//		criteria.createAlias("authorUser", "au");
//		criteria.createAlias("approvalUser", "app");
//		criteria.createAlias("updateUser", "up");
//		if ("reviewer".equals(listUser.getUserType())) {
//			criteria.add(Restrictions.eq("au.branch", listUser.getBranch()));
//			//
//			criteria.add(Restrictions.or(
//					Restrictions.and(Restrictions.eq("status", "Draft"), Restrictions.ne("au.userId", userId), Restrictions.isNull("app.userId")),
//					Restrictions.and(Restrictions.eq("status", "Draft"), Restrictions.ne("up.userId", userId), Restrictions.isNotNull("app.userId"))));
//		} else {
//			criteria.add(Restrictions.eq("au.userId", listUser.getUserId()));
//			
//			criteria.add(Restrictions.and(Restrictions.eq("status", "Draft"), Restrictions.isNotNull("app.userId")));
//			//criteria.add(Restrictions.isNull("app.userId"));
//		}
//
//		criteria.addOrder(Order.desc("addTime"));
		
		List<TNews> tlist = new ArrayList<TNews>();
		boolean bool = TransactSQLInjectionUtil.sql_inj(StringUtil.toString(keyword)); //防止SQL注入
		if(bool){
			return tlist;
		}else{
			StringBuffer sql = new StringBuffer();
			sql.append("select t.* from t_news t");
			sql.append(" left join t_user app on t.approval_user_id = app.user_id");
			sql.append(" left join t_user au on t.author_user_id = au.user_id");
			
			if ("reviewer".equals(listUser.getUserType())) {
				sql.append(" left join t_user up on t.update_user_id = up.user_id");
				sql.append(" where au.branch ='"+listUser.getBranch()+"'");
				
				sql.append(" and !(");
				sql.append(" (");
				sql.append(" t. status ='Draft'");
				sql.append(" and t.author_user_id <>'"+userId+"'");
				sql.append(" and t.approval_user_id is null");
				sql.append(" )");
				sql.append(" or (");
				sql.append(" t. status ='Draft'");
				sql.append(" and t.update_user_id <>'"+userId+"'");
				sql.append(" and t.approval_user_id is not null");
				sql.append(" )");
				sql.append(" )");
			} else {
				sql.append(" left join t_user up on t.update_user_id = up.user_id");
				
				sql.append(" where t.author_user_id ='"+userId+"'");
				sql.append(" and !(t. status ='Draft' and t.approval_user_id is not null and  t.update_user_id <>'"+userId+"')");
			}
			
			if (StringUtils.isNotBlank(keyword)) {
				sql.append(" and (t.title like '%"+keyword+"%' or t.content like '%"+keyword+"%')");
			}
			
			if (StringUtils.isNotBlank(tagName)) {
				// 分割tag标签
				String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
				List<String> tagNames = StringUtil.split(tagName, charSet);
				String tagNameStr="";
				for(int i=0;i<tagNames.size();i++){
					tagNameStr+="'"+StringUtil.toString(tagNames.get(i))+"',";
				}
				String tagSql = "select t.tag_id from t_tags t where t.name in("+tagNameStr.substring(0, tagNameStr.length()-1)+")";
				String tagIds = "";
				List<Map<String, Object>> listMap=this.jdbcTemplate.queryForList(tagSql);
				if(listMap!=null && listMap.size()>0){
					for(int i=0;i<listMap.size();i++){
						tagIds+="'"+StringUtil.toString(listMap.get(i).get("tag_id"))+"',";
					}
				}
				String newsIds = "";
				String newsSql = "select distinct t.news_id from t_new_tag  t where t.tag_id in("+tagIds.substring(0, tagIds.length()-1)+")";
				List<Map<String, Object>> listMap_videoId=this.jdbcTemplate.queryForList(newsSql);
				if(listMap_videoId!=null && listMap_videoId.size()>0){
					for(int i=0;i<listMap_videoId.size();i++){
						newsIds+="'"+StringUtil.toString(listMap_videoId.get(i).get("news_id"))+"',";
					}
					sql.append(" and t.news_id in("+newsIds.substring(0, newsIds.length()-1)+")");
				}else{
					sql.append(" and t.news_id in('')");
				}
			}
			
			
			if (StringUtils.isNotBlank(fromDate) && StringUtils.isNotBlank(toDate)) {
				sql.append("  and t.add_time>='"+DateUtil.dateToString(this.updateDate(this.getDate(fromDate), "start"))+"' and t.add_time<='"+DateUtil.dateToString(this.updateDate(this.getDate(toDate), "end"))+"'");
			} else if (StringUtils.isNotBlank(fromDate)) {
				sql.append("  and t.add_time>='"+DateUtil.dateToString(this.updateDate(this.getDate(fromDate), "start"))+"'");
			} else if (StringUtils.isNotBlank(toDate)) {
				sql.append("  and t.add_time<='"+DateUtil.dateToString(this.updateDate(this.getDate(toDate), "end"))+"'");
			}
			sql.append(" order by t.add_time desc");
			//System.out.println("****************"+sql.toString());
			tlist = (List<TNews>) this.getListBySql(pager, sql.toString(),TNews.class);
		
			//add by william 2014-12-11
			for (int i = 0; i < tlist.size(); i++) {
				TNews tnews = tlist.get(i);
				Criteria newsImageCriteria = getCriteria(TNewsImage.class);
				newsImageCriteria.add(Restrictions.eq("newsId", tnews.getNewsId()));
				newsImageCriteria.addOrder(Order.asc("orderIndex"));
				tnews.setImageList(newsImageCriteria.list());
				
				//add by Bing 2015-08-05
				Set<TTags> tagset = tnews.getTTagses();
				Iterator it=tagset.iterator();
				String haveNowTagFlag="noNowTag";
				
				while(it .hasNext() ){
					TTags tag=(TTags) it.next();
					if("NOW".equals(tag.getName())){
						haveNowTagFlag="haveNowTag";
						break;
					}
				}
				tnews.setHaveNowTagFlag(haveNowTagFlag);
				
				//add by Bing 2015-08-05
				String content = StringUtil.toStringNoTrim(tnews.getContent());
				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
					tnews.setVideoFlag("video");
				}else{
					tnews.setVideoFlag("notvideo");
				}
				
				//设置点赞数量   Add by Bing 2015-07-07
				String likeSql="select count(t.id) num from t_like t where  t.contentId='"+tnews.getNewsId()+"' and t.delete_flag='0'";
				List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
				if(listMapLike!=null && listMapLike.size()>0){
					tnews.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
				}else{
					tnews.setLikeAmount(0);
				}
				
				//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
				String islikeSql="select count(t.id) num from t_like t where  t.contentId='"+tnews.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
				List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
				Integer amount=0;
				if(listMapIsLike!=null && listMapIsLike.size()>0){
					amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
				}else{
					amount=0;
				}
				if(amount>0){
					tnews.setLike(true);
				}else{
					tnews.setLike(false);
				}
				
				//设置浏览数量  Add by Bing 2015-07-07
				tnews.setBrowseTimes(logService.getBrowseTimes(tnews.getNewsId()+"", "", userId));
				
				//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
				tnews.setAllBrowseTimes(logService.getAllBrowseTimes(tnews.getNewsId()+"", "", userId));
				
				//设置评论  Add by Bing 2015-07-07
//				List<TComments> commentList = new ArrayList<TComments>();
//				String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.contentId='"+tnews.getNewsId()+"' order by t.publish_time desc";
//				List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//				if(listMapComment!=null && listMapComment.size()>0){
//					for(int k=0;k<listMapComment.size();k++){
//						TComments comment=new TComments();
//						comment.setId(StringUtil.toString(listMapComment.get(k).get("id")));
//						String userid=StringUtil.toString(listMapComment.get(k).get("userId"));
//						comment.setUserId(userid);
//						//审批人员可以删除评论
//						if (listUser.getRole().indexOf("Console Admin") == -1) {
//							comment.setCanDelete(false);
//						}else{
//							comment.setCanDelete(true);
//						}
//						
//						comment.setUserName(StringUtil.toString(listMapComment.get(k).get("user_name")));
//						comment.setContentId(StringUtil.toString(listMapComment.get(k).get("contentId")));
//						comment.setComments(StringUtil.toString(listMapComment.get(k).get("comments")));
//						String pubDate = StringUtil.toString(listMapComment.get(k).get("publish_time"));
//						comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//						
//						commentList.add(comment);
//					}
//					tnews.setCommentList(commentList);
//				}
//				
//				//设置评论数量  Add by Bing 2015-07-07
//				tnews.setCommentAmount(commentList.size());
			}
			return tlist;
		}
	}

	@Override
	public Object editNews(TNews news, String tags, String userId,String toBePostedTime,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.updateUserNull");

		// 分割tag标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		TNews tNews = null;
		if (news.getNewsId() == null) {
			throw new ValidateException("news.newsIdIsNull");
		}
		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}
//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		if (news != null && news.getNewsId()!=null) {
			tNews = findEntity(TNews.class, news.getNewsId());
			if (tNews != null) {
				// 审核通过的新闻只有发布者与审核者才能编辑
				if ("Published".equals(tNews.getStatus())) {
					if (!"reviewer".equals(loginUser.getUserType())) {
						throw new ValidateException("news.notAuthor");
					}
					// 设置新闻的状态
					if(news.getStatus().equals("Draft")){
						tNews.setStatus("Draft");
					}else if(news.getStatus().equals("Submit")){
						tNews.setStatus("Pending Review");
						tNews.setSubmit_time(new Timestamp(new Date().getTime()));
					}else if(news.getStatus().equals("Publish")){
						if (!"reviewer".equals(loginUser.getUserType())) {
							throw new ValidateException("common.illegalRequest");
						}
						tNews.setApprovalUser(loginUser);
						tNews.setApprovalTime(new Timestamp(new Date().getTime()));
						tNews.setStatus("Published");
					}
				} else {
					// 新闻为草稿，只能是发布者才能修改
//					if ("Draft".equals(tNews.getStatus())) {
//						if (!userId.equals(tNews.getAuthorUser().getUserId())) {
//							throw new ValidateException("news.notAuthor");
//						}
//					}
					// 新闻等待审核状态，只有审核人员才能修改
					if ("Pending Review".equals(tNews.getStatus())) {
						if ("reporter".equals(loginUser.getUserType())) {
							throw new ValidateException("news.pedingNotRight");
						}
					}
					
				}
			}
			
			if (StringUtils.isBlank(news.getTitle())) {
				throw new ValidateException("news.titleNull");
			}
			if (StringUtils.isBlank(news.getPic())) {
				throw new ValidateException("news.picIsNull");
			}
			if (StringUtils.isNotEmpty(news.getBriefContent())) {
				if (news.getBriefContent().length() > 150) {
					throw new ValidateException("news.briefContentIsLong");
				}
			}
			if (StringUtils.isBlank(news.getBriefContent()))
				throw new ValidateException("news.briefContentIsNull");
			if (StringUtils.isBlank(news.getContent()))
				throw new ValidateException("news.contentNull");
			if (StringUtils.isBlank(tags)) {
				throw new ValidateException("news.tagsNull");
			}
			if (StringUtils.isNotBlank(news.getContent())) {
				tNews.setContent(news.getContent());
			}
			if (StringUtils.isNotBlank(news.getTitle())) {
				tNews.setTitle(news.getTitle());
			}
			if (StringUtils.isNotBlank(news.getBriefContent())) {
				tNews.setBriefContent(news.getBriefContent());
			}
			if (StringUtils.isNotBlank(news.getPic())) {
				tNews.setPic(news.getPic());
			}

			if (StringUtils.isNotBlank(tags)) {
				List<String> tagNames = StringUtil.split(tags, charSet);
				// tNews.getTTagses().removeAll(tNews.getTTagses());
				// 设置Tags
				Set<TTags> tages = new HashSet<TTags>();
				for (String tagName : tagNames) {
					TTags tag = null;
					Criteria tagCriteria = getCriteria(TTags.class);
					tagCriteria.add(Restrictions.eq("name", tagName));
					List<?> userList = tagCriteria.list();
					if (userList.size() > 1 || userList.size() < 0) {
						// new ValidateException("common.sysException");
						continue;
					} else if (userList.size() == 0) {
						tag = new TTags();
						tag.setTagId(CreateID.getID());
						tag.setName(tagName);
					} else if (userList.size() == 1) {
						tag = (TTags) userList.get(0);
					}

					tages.add(tag);
				}
				tNews.setTTagses(tages);
			}
			// 设置修改人员
			tNews.setUpdateUser(loginUser);
			// 设置修改时间
			tNews.setEditTime(new Timestamp(new Date().getTime()));

			//tNews.setAddTime(new Timestamp(new Date().getTime()));
			//
			if(StringUtils.isNotBlank(toBePostedTime)&&!toBePostedTime.equals("NaN")){
				tNews.setToBePostedTime(new Timestamp(Long.valueOf(toBePostedTime)));
			}else{
				tNews.setToBePostedTime(new Timestamp(new Date().getTime()));
			}
			// 设置新闻的状态
			if ("reviewer".equals(loginUser.getUserType())) {
				tNews.setStatus("Published");
				tNews.setApprovalUser(loginUser);
				tNews.setApprovalTime(new Timestamp(new Date().getTime()));
			} else {
				tNews.setStatus("Pending Review");
				tNews.setSubmit_time(new Timestamp(new Date().getTime()));
			}
			
			// 设置新闻类型
			tNews.setType("news");
//			String content = StringUtil.toStringNoTrim(tNews.getContent());
//			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//				tNews.setType("video");
//			}else{
//				tNews.setType("news");
//			}
			if(tNews.getPush_count()==null){
				tNews.setPush_count(0);
			}
	    	if(push==null||"".equals(push)){
	    		tNews.setPush("no");
	    	}else{
	    		tNews.setPush(push);
	    	}
	    	tNews.setSubmit_time(new Timestamp(new Date().getTime()));
			tNews.setSubmit_user_id(userId);
			if (StringUtils.isNotBlank(tNews.getContent())){
				tNews.setContent(ReplaceUtil.replaceSomeString(tNews.getContent(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
			}
			tNews.setPushInfo(pushcontent);
			
			//推送
			if("Published".equals(tNews.getStatus())){
				if("push".equals(push)&&tNews.getPush_count()==0){//是否push
					//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "ios", null,"new", tNews.getNewsId()+"");
					//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "android", null, "new", tNews.getNewsId()+"");
					BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"new", tNews.getNewsId()+"");
					BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "new", tNews.getNewsId()+"");
					Integer push_count=0;
					if(tNews.getPush_count()!=null){
						push_count=tNews.getPush_count();
					}
					tNews.setPush_count(push_count+1);
					//updateEntity(tNews);
				}
			}
			
			updateEntity(tNews);
		}
		if (tNews != null) {
			return tNews;
		} else {
			throw new ValidateException("news.newsNoExist");
		}
		//return null;
	}

	@SuppressWarnings("unused")
	@Override
	public boolean delNews(String id, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.updateUserNull");

		TNews tNews = null;
		TUser loginUser = findEntity(TUser.class, userId);
		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		/*
		 * 判断是reviewer（审核者）还是reporter（发布者）
		 * reviewer除了别人的草稿，身下自己部门的所有新闻和自己的草稿新闻都可以删除
		 * reporter用户只可以删除自己的草稿
		 */
        //start
		if (StringUtils.isNotBlank(id)) {
			tNews = findEntity(TNews.class, Integer.parseInt(id));
			TUser newuser=tNews.getAuthorUser();
			if (tNews != null) {
//				if("reviewer".equals(loginUser.getUserType())){
//					//判断新闻是不是自己部门发布的
//					if(newuser!=null){
//						if(loginUser.getBranch().equals(newuser.getBranch())){
//							//如果是别人的草稿
//							if("Draft".equals(tNews.getStatus())){
//								if(!newuser.getUserId().equals(loginUser.getUserId())){
//									//不是 自己的草稿，异常回馈
//									throw new ValidateException("news.authorError");
//								}
//							}
//						}else{
//							//不是同一个部门的，异常回馈
//							throw new ValidateException("news.deptError");
//						}
//					}
//				}else 
				if("reporter".equals(loginUser.getUserType())){
					if("Draft".equals(tNews.getStatus())){
						if(!newuser.getUserId().equals(loginUser.getUserId())){
							//只能删除自己的草稿，异常回馈
						}
					}else{
						//reporter用户只能删除草稿，异常回馈
						throw new ValidateException("news.isDeleteDraft");
					}
				}
				//end
			}else{
				throw new ValidateException("news.newsNoExist");
			}
		}
		return deleteEntity(tNews);
	}

	@Override
	public Object assignToBeacon(String newsId, String beaconId) throws Exception {
		// 判断新闻id为空
		if (StringUtils.isBlank(newsId)) {
			throw new ValidateException("news.assignNewsIdNull");
		}
		// 判断beaconid为空
		if (StringUtils.isBlank(beaconId)) {
			throw new ValidateException("news.assignBeaconIdNull");
		}
		TNews tNews = (TNews) getSession().get(TNews.class, Integer.parseInt(newsId));
		if (tNews == null) {
			throw new ValidateException("news.assignNewsNoExits");
		}
		TBeacon tBeacon = (TBeacon) getSession().get(TBeacon.class, beaconId);
		if (tBeacon == null) {
			throw new ValidateException("news.assignBeaconNoExits");
		}

		TNews beacon_news = tBeacon.getTnews();
		// 判断这个beacon是否已经绑定,
		// 1、没有绑定
		if (beacon_news == null) {
			if (!"announcement".equals(tNews.getType())) {
				tNews.setType("announcement");
				updateEntity(tNews);
			}
			tBeacon.setTnews(tNews);
			updateEntity(tBeacon);
		} else {// 2、绑定了新闻
			tBeacon.setTnews(tNews);
			updateEntity(tBeacon);
			// 2.1、判断这个新闻是否还绑定其他的beacon
			if (beacon_news.getTBeacons().size() <= 1) {
				tNews.setType("news");
//				String content = StringUtil.toStringNoTrim(tNews.getContent());
//				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//					tNews.setType("video");
//				}else{
//					tNews.setType("news");
//				}
				updateEntity(tNews);
			}
		}

		return tBeacon;

	}

	@Override
	public Object auditNewsStatus(String newsId, String status, String userId,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.approvalUserNull");

		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

		if (!"reviewer".equals(loginUser.getUserType())) {
			throw new ValidateException("news.pedingNotRight");
		}
		TNews tNews = null;
		if (StringUtils.isNotBlank(newsId)) {
			tNews = findEntity(TNews.class, Integer.parseInt(newsId));
			if (tNews != null) {
				tNews.setStatus(status);
				tNews.setApprovalUser(loginUser);
				// 设置审批时间
				tNews.setApprovalTime(new Timestamp(new Date().getTime()));
				if(tNews.getPush_count()==null){
					tNews.setPush_count(0);
				}
		    	if(push==null||"".equals(push)){
		    		tNews.setPush("no");
		    	}else{
		    		tNews.setPush(push);
		    	}
//		    	String content = StringUtil.toStringNoTrim(tNews.getContent());
//				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//					tNews.setType("video");
//				}else{
//					tNews.setType("news");
//				}
		    	if (StringUtils.isNotBlank(tNews.getContent())){
		    		tNews.setContent(ReplaceUtil.replaceSomeString(tNews.getContent(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
		    	}
		    	tNews.setPushInfo(pushcontent);
		    	
				//推送
				if("Published".equals(tNews.getStatus())){
					if("push".equals(push)&&tNews.getPush_count()==0){//是否push
						//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "ios", null,"new", tNews.getNewsId()+"");
						//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "android", null, "new", tNews.getNewsId()+"");
						BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"new", tNews.getNewsId()+"");
						BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "new", tNews.getNewsId()+"");
						Integer push_count=0;
						if(tNews.getPush_count()!=null){
							push_count=tNews.getPush_count();
						}
						tNews.setPush_count(push_count+1);
						//updateEntity(tNews);
					}
				}
				updateEntity(tNews);
			}
		}
		if (tNews != null) {
			return tNews;
		} else {
			throw new ValidateException("news.newsNoExist");
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object listPeding(Pager pager, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.approvalUserNull");
		// 得到审批者的信息
		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

		if (!"reviewer".equals(loginUser.getUserType())) {
			throw new ValidateException("news.pedingNotRight");
		}
		Criteria criteria = getCriteria(TNews.class);
		//criteria.add(Restrictions.eq("type", "news"));
		criteria.add(Restrictions.eq("status", "Pending Review"));

		criteria.createAlias("authorUser", "au");
		criteria.add(Restrictions.eq("au.branch", loginUser.getBranch()));

		criteria.addOrder(Order.desc("addTime"));

		List<TNews> tlist = (List<TNews>)listPageQBCL(criteria, pager);
		List<TNews> list = new ArrayList<TNews>();
		for (int i = 0; i < tlist.size(); i++) {
			TNews tnews = tlist.get(i);
			Criteria newsImageCriteria = getCriteria(TNewsImage.class);
			newsImageCriteria.add(Restrictions.eq("newsId", tnews.getNewsId()));
			newsImageCriteria.addOrder(Order.asc("orderIndex"));
			tnews.setImageList(newsImageCriteria.list());
			
			//add by Bing 2015-08-05
			Set<TTags> tagset = tnews.getTTagses();
			Iterator it=tagset.iterator();
			String haveNowTagFlag="noNowTag";
			
			while(it .hasNext() ){
				TTags tag=(TTags) it.next();
				if("NOW".equals(tag.getName())){
					haveNowTagFlag="haveNowTag";
					break;
				}
			}
			tnews.setHaveNowTagFlag(haveNowTagFlag);
			
			//add by Bing 2015-08-05
			String content = StringUtil.toStringNoTrim(tnews.getContent());
			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
				tnews.setVideoFlag("video");
			}else{
				tnews.setVideoFlag("notvideo");
			}
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="select count(t.id) num from t_like t where  t.contentId='"+tnews.getNewsId()+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tnews.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tnews.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="select count(t.id) num from t_like t where  t.contentId='"+tnews.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tnews.setLike(true);
			}else{
				tnews.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			tnews.setBrowseTimes(logService.getBrowseTimes(tnews.getNewsId()+"", "", userId));
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			tnews.setAllBrowseTimes(logService.getAllBrowseTimes(tnews.getNewsId()+"", "", userId));
			
			//设置评论  Add by Bing 2015-07-07
//			List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.contentId='"+tnews.getNewsId()+"' order by t.publish_time desc";
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int k=0;k<listMapComment.size();k++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(k).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(k).get("userId"));
//					comment.setUserId(userid);
//					//审批人员可以删除评论
//					if (!"reviewer".equals(loginUser.getUserType())) {
//						comment.setCanDelete(false);
//					}else{
//						comment.setCanDelete(true);
//					}
//					comment.setUserName(StringUtil.toString(listMapComment.get(k).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(k).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(k).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(k).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tnews.setCommentList(commentList);
//			}
//			
//			//设置评论数量  Add by Bing 2015-07-07
//			tnews.setCommentAmount(commentList.size());
			list.add(tnews);
		}
		return list;
	}

	@Override
	public Object auditPublished(TNews news, String tags, String userId,String toBePostedTime,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.approvalUserNull");

		if (news.getNewsId() == null) {
			throw new ValidateException("news.newsIdIsNull");
		}

		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		if (!"reviewer".equals(loginUser.getUserType())) {
			throw new ValidateException("news.pedingNotRight");
		}
		TNews tNews = null;
		if (news != null && StringUtils.isNotBlank(news.getNewsId().toString())) {
			tNews = findEntity(TNews.class, news.getNewsId());
			if (tNews != null) {

				if ("Published".equals(tNews.getStatus())) {
					throw new ValidateException("news.publishedNotUpdate");
				}

				if (StringUtils.isNotBlank(news.getContent())) {
					tNews.setContent(news.getContent());
				}
				if (StringUtils.isNotBlank(news.getTitle())) {
					tNews.setTitle(news.getTitle());
				}
				if (StringUtils.isNotBlank(news.getBriefContent())) {
					tNews.setBriefContent(news.getBriefContent());
				}
				if (StringUtils.isNotBlank(news.getPic())) {
					tNews.setPic(news.getPic());
				}

				if (StringUtils.isNotBlank(tags)) {
					String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };

					List<String> tagNames = StringUtil.split(tags, charSet);

					// 设置Tags
					Set<TTags> tages = new HashSet<TTags>();
					for (String tagName : tagNames) {
						TTags tag = null;
						Criteria tagCriteria = getCriteria(TTags.class);
						tagCriteria.add(Restrictions.eq("name", tagName));
						// tagCriteria.add(Restrictions.eq("name",
						// tagName));
						List<?> userList = tagCriteria.list();
						if (userList.size() > 1 || userList.size() < 0) {
							// new ValidateException("common.sysException");
							continue;
						} else if (userList.size() == 0) {
							tag = new TTags();
							tag.setTagId(CreateID.getID());
							tag.setName(tagName);
						} else if (userList.size() == 1) {
							tag = (TTags) userList.get(0);
						}

						tages.add(tag);
					}
					tNews.getTTagses().removeAll(tNews.getTTagses());
					tNews.setTTagses(tages);
				}
				// 设置修改人员
				tNews.setUpdateUser(loginUser);
				// 设置修改时间
				tNews.setEditTime(new Timestamp(new Date().getTime()));

				tNews.setStatus("Published");
				if(tNews.getSubmit_user_id()==null){
					tNews.setSubmit_time(new Timestamp(new Date().getTime()));
					tNews.setSubmit_user_id(userId);
				}
				tNews.setApprovalUser(loginUser);
				// 设置审批时间
				tNews.setApprovalTime(new Timestamp(new Date().getTime()));
				//
				if(StringUtils.isNotBlank(toBePostedTime)&&!toBePostedTime.equals("NaN")){
					news.setToBePostedTime(new Timestamp(Long.valueOf(toBePostedTime)));
				}else{
					news.setToBePostedTime(new Timestamp(new Date().getTime()));
				}
				
				// 设置新闻类型
				tNews.setType("news");
//				String content = StringUtil.toStringNoTrim(tNews.getContent());
//				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
//					tNews.setType("video");
//				}else{
//					tNews.setType("news");
//				}
				if(tNews.getPush_count()==null){
					tNews.setPush_count(0);
				}
		    	if(push==null||"".equals(push)){
		    		tNews.setPush("no");
		    	}else{
		    		tNews.setPush(push);
		    	}
		    	if (StringUtils.isNotBlank(tNews.getContent())){
		    		tNews.setContent(ReplaceUtil.replaceSomeString(tNews.getContent(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
		    	}
		    	tNews.setPushInfo(pushcontent);
				
				//推送
				if("Published".equals(tNews.getStatus())){
					if("push".equals(push)&&tNews.getPush_count()==0){//是否push
						//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "ios", null,"new", tNews.getNewsId()+"");
						//this.push_bd(tNews.getTitle(), tNews.getBriefContent(), "android", null, "new", tNews.getNewsId()+"");
						BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"new", tNews.getNewsId()+"");
						BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "new", tNews.getNewsId()+"");
						Integer push_count=0;
						if(tNews.getPush_count()!=null){
							push_count=tNews.getPush_count();
						}
						tNews.setPush_count(push_count+1);
						//updateEntity(tNews);
					}
				}
				
				updateEntity(tNews);
			}
		}
		if (tNews != null) {
			return tNews;
		} else {
			throw new ValidateException("news.newsNoExist");
		}
	}

	/**
	 * 传递时间戳转换成日期型
	 * 
	 * @param unixDate
	 * @return
	 * @throws Exception
	 */
	private Date getDate(String unixDate) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long unixLong = 0;
		Date date = new Date();
		try {
			unixLong = Long.parseLong(unixDate) * 1000;
		} catch (Exception ex) {
			throw new ValidateException("news.requestDateError");
		}
		try {
			date = format.parse(format.format(unixLong));
		} catch (Exception ex) {
			throw new ValidateException("news.requestDateError");
		}
		return date;
	}
	/**
	 * 将日期的开始时间和结束时间重置
	 * @param date
	 * @param startOrEnd
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	private Date updateDate(Date date,String startOrEnd){
		if("start".equals(startOrEnd)){
			date.setHours(00);
			date.setMinutes(00);
			date.setSeconds(00);
		}else{
			date.setHours(23);
			date.setMinutes(59);
			date.setSeconds(59);
		}
		return date;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object getNewsDetialInfo(String newId, String type, String userId,String appOrPCFlag)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");
		TNews tNews=null;
		if(StringUtils.isNotBlank(newId)){
			tNews = findEntity(TNews.class, Integer.parseInt(newId));
			 if(tNews==null){
				 throw new ValidateException("news.unExist"); 
			 }
			 
			//add by Bing 2015-08-05
			Set<TTags> tagset = tNews.getTTagses();
			Iterator it=tagset.iterator();
			String haveNowTagFlag="noNowTag";
				
			while(it .hasNext() ){
				TTags tag=(TTags) it.next();
				if("NOW".equals(tag.getName())){
					haveNowTagFlag="haveNowTag";
					break;
				}
			}
			tNews.setHaveNowTagFlag(haveNowTagFlag);
			 
			//add by Bing 2015-08-05
			String content = StringUtil.toStringNoTrim(tNews.getContent());
			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
				tNews.setVideoFlag("video");
			}else{
				tNews.setVideoFlag("notvideo");
			}
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="";
			if(type==null||"".equals(type)){
				likeSql="select count(t.id) num from t_like t where  t.contentId='"+tNews.getNewsId()+"' and t.delete_flag='0'";
			}else{
				likeSql="select count(t.id) num from t_like t where t.type='"+type+"' and t.contentId='"+tNews.getNewsId()+"' and t.delete_flag='0'";
			}
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tNews.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tNews.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="";
			if(type==null||"".equals(type)){
				islikeSql="select count(t.id) num from t_like t where  t.contentId='"+tNews.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			}else{
				islikeSql="select count(t.id) num from t_like t where t.type='"+type+"' and t.contentId='"+tNews.getNewsId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			}
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tNews.setLike(true);
			}else{
				tNews.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			if(type==null||"".equals(type)){
				tNews.setBrowseTimes(logService.getBrowseTimes(tNews.getNewsId()+"", "", userId));
			}else{
				tNews.setBrowseTimes(logService.getBrowseTimes(tNews.getNewsId()+"", type, userId));
			}
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			if(type==null||"".equals(type)){
				tNews.setAllBrowseTimes(logService.getAllBrowseTimes(tNews.getNewsId()+"", "", userId));
			}else{
				tNews.setAllBrowseTimes(logService.getAllBrowseTimes(tNews.getNewsId()+"", type, userId));
			}
			
			
			//设置评论  Add by Bing 2015-07-07
//			List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="";
//			if(type==null||"".equals(type)){
//				commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.contentId='"+tNews.getNewsId()+"' order by t.publish_time desc";
//			}else{
//				commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='"+type+"' and t.contentId='"+tNews.getNewsId()+"' order by t.publish_time desc";
//			}
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int i=0;i<listMapComment.size();i++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//					comment.setUserId(userid);
//					//登录人可以删除自己的评论，不能删除其他人的
//					if(userid.equals(userId)){
//						comment.setCanDelete(true);
//					}else{
//						comment.setCanDelete(false);
//					}
//					comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tNews.setCommentList(commentList);
//			}
			
			//设置评论数量  Add by Bing 2015-07-07
			//tNews.setCommentAmount(commentsService.getCommentsAmount(tNews.getNewsId()+"", ""));
			
			if("PC".equals(appOrPCFlag)){
				tNews.setCommentAmount(commentsService.getAllCommentsAmount(tNews.getNewsId()+"", ""));
			}else{
				tNews.setCommentAmount(commentsService.getCommentsAmount(tNews.getNewsId()+"", ""));
			}
			
			//设置提交人名字
			if(StringUtils.isNotBlank(tNews.getSubmit_user_id())){
				TUser submitUser = findEntity(TUser.class, tNews.getSubmit_user_id());
				tNews.setSubmit_user_name(submitUser.getUserName());
			}
			
		}else{
			throw new ValidateException("news.unExist");
		}
		return tNews;
	}
}
